package flexibilityDesign;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import util.Lang;

public class CriticalScenarioDetect {
	private int n;// plant number
	private int m;// product number
	private int simulationCount;// sampling number

	private double[][] demands;// clustered demands
	private double[] capacities;// capacities of plants

	public CriticalScenarioDetect(int n, int m, int simulationCount,
			double[][] demands, double[] caps) {
		this.n = n;
		this.m = m;
		this.demands = demands;
		this.capacities = caps;
		this.simulationCount = simulationCount;
	}

	/**
	 * If r=f(dedicated)/f(fully)=1, drop this scenario
	 * **/
	public double[][] filter() {
		int[] filteredIndex = new int[demands.length];

		double totalCap = 0.0;
		for (int i = 0; i < n; i++)
			totalCap += capacities[i];

		int remained = 0;
		for (int k = 0; k < simulationCount; k++) {
			double dFlow = 0.0;
			double tFlow = 0.0;
			double tDemand = 0.0;
			for (int i = 0; i < n; i++) {
				if (capacities[i] > demands[k][i])
					dFlow += demands[k][i];
				else
					dFlow += capacities[i];
				tDemand += demands[k][i];
			}
			tFlow = tDemand > totalCap ? totalCap : tDemand;
			double ratio = BigDecimal
					.valueOf(dFlow)
					.divide(BigDecimal.valueOf(tFlow), 5,
							BigDecimal.ROUND_HALF_EVEN).doubleValue();
			if (ratio == 1.0)
				filteredIndex[k] = 1;
			else {
				filteredIndex[k] = 0;
				remained++;
			}
		}
		double[][] result = new double[remained][];
		int resultIdx = 0;
		for (int i = 0; i < filteredIndex.length; i++) {
			if (filteredIndex[i] == 0) {
				result[resultIdx] = Lang.clone(demands[i]);
				resultIdx++;
			}
		}
		System.out.println("@before filter size=" + demands.length
				+ "; after size=" + result.length);
		return result;
	}

	public List<Double> maxFlow() {
		List<Double> ratios = new ArrayList<>();

		double totalCap = 0.0;
		for (int i = 0; i < n; i++)
			totalCap += capacities[i];

		for (int k = 0; k < simulationCount; k++) {
			double dFlow = 0.0;
			double tFlow = 0.0;
			double tDemand = 0.0;
			for (int i = 0; i < n; i++) {
				if (capacities[i] > demands[k][i])
					dFlow += demands[k][i];
				else
					dFlow += capacities[i];
				tDemand += demands[k][i];
			}
			tFlow = tDemand > totalCap ? totalCap : tDemand;
			double ratio = BigDecimal
					.valueOf(dFlow)
					.divide(BigDecimal.valueOf(tFlow), 5,
							BigDecimal.ROUND_HALF_EVEN).doubleValue();
			int index = 0;
			for (index = 0; index < ratios.size(); index++) {
				if (ratios.get(index) > ratio)
					break;
			}
			ratios.add(index, ratio);
		}
		return ratios;
	}
}
